﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HPPClientLibrary;
using HPPUtil;
using HPPUtil.Helpers;

namespace HPPClientUI
{
    using HPPClientLibrary.DownLoad;

    public partial class FrmMain : MyFormBase
    {

        #region Fields

        private static object _syncRoot = new object();
        private static HPPClient _client;

        private ContextMenuStrip _menuStrip;

        private Dictionary<string, ListViewItem> _hashListViewItemDict;

        #endregion

        #region Properties

        public static HPPClient Client
        {
            get
            {
                if (_client == null)
                {
                    lock (_syncRoot)
                    {
                        if (_client == null)
                        {
                            _client = new HPPClient();
                            return _client;
                        }        
                    }
                }
                return _client;
            }
        }

        public ListView DownloadList
        {
            get { return this.lvDownload; }
        }

        public ListView SearchResultList
        {
            get { return this.lvSearchResult;  }
        }

        public List<DownMsg> DownloadListView
        {
            internal get { throw new NotSupportedException(); }
            set
            {
                List<DownMsg> downMsgs = value;


                foreach (DownMsg msg in downMsgs)
                {
                    DownMsg downMsg = msg;
                    SafeInvoke(() =>
                    {
                        ListViewItem viewItem;
                        lock (_hashListViewItemDict)
                        {
                            if (!_hashListViewItemDict.ContainsKey(downMsg.Hash))
                            {
                                viewItem = new ListViewItem(new string[] { downMsg.FileName, GetFileLenString(downMsg.FileLen), GetPercentString(downMsg.Percent) });

                                _hashListViewItemDict.Add(downMsg.Hash, viewItem);
                                DownloadList.Items.Add(viewItem);

                            }
                            else
                            {
                                viewItem = _hashListViewItemDict[downMsg.Hash];

                            }
                        }

                        //viewItem.SubItems[0].Text = downMsg.FileName;
                        //viewItem.SubItems[1].Text = GetFileLenString(downMsg.FileLen);
                        viewItem.SubItems[2].Text = GetPercentString(downMsg.Percent);


                    });
                    

                }
                
                    

                    
                }

                

            
        }

        public List<SearchResult> SearchResultListView
        {
            internal get { throw new NotSupportedException(); }
            set
            {
                lock (SearchResultList)
                {
                    SafeInvoke(() =>
                    {
                        List<SearchResult> downMsgs = value;

                        SearchResultList.Items.Clear();

                        ListViewItem[] itemArray = downMsgs.Cast(s => new ListViewItem(new string[]
                                                                                           {
                                                                                               s.FileName,
                                                                                               //GetFileLenString(s.FileLen),
                                                                                               s.Hash,


                                                                                           })).ToArray();

                        SearchResultList.Items.AddRange(itemArray);
                        
                    });


                }



            }
        }

        #endregion


        public FrmMain()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            _hashListViewItemDict = new Dictionary<string, ListViewItem>();

            BindProxy.AddBind(this, StaticHelper.GetPropertyName<FrmMain>(o => o.DownloadListView), FrmMain.Client.DownloadManager, StaticHelper.GetPropertyName<DownloadManager>(o => o.DownloadInfos), null);

            BindProxy.AddBind(this, StaticHelper.GetPropertyName<FrmMain>(o => o.SearchResultListView), FrmMain.Client, StaticHelper.GetPropertyName<HPPClient>(o => o.SearchResult), null);

            this.DownloadListView = Client.DownloadManager.DownloadInfos;

            _menuStrip = new ContextMenuStrip();
            ToolStripMenuItem menuItem = new ToolStripMenuItem("下载", null, (send, args) =>
                                                                           {
                                                                               ListView.SelectedListViewItemCollection collection = this.lvSearchResult.SelectedItems;

                                                                               foreach (ListViewItem item in collection)
                                                                               {
                                                                                   if (item.SubItems[0] == null || item.SubItems[1] == null)
                                                                                   {
                                                                                       continue;

                                                                                   }

                                                                                   string filename = item.SubItems[0].Text.Trim();
                                                                                   string hash = item.SubItems[1].Text.Trim();
                                                                                   FrmMain.Client.Download(hash, filename, true);
                                                                               }
                                                                           });

            _menuStrip.Items.Add(menuItem);
            SearchResultList.ContextMenuStrip = _menuStrip;
            Client.Init();
            Client.StartListen();
        }



        private string GetSpeedString(int speed)
        {
            if (speed < 1024)
            {
                return string.Format("{0}B/s", speed);
            }
            else if (speed < 1048576)
            {
                return string.Format("{0}KB/s", (double) speed/1024);
            }


            return string.Format("{0}MB/s", (double) speed/1073741824);
        }

        private string GetPercentString(double percent)
        {
            return string.Format("{0} %", Math.Round(percent, 1));
        }

        private string GetFileLenString(long fileLen)
        {
            if (fileLen < 1024)
            {
                return string.Format("{0}B", fileLen);
            }
            else if (fileLen < 1048576)
            {
                return string.Format("{0}KB", fileLen / 1024);
            }
            else if (fileLen < 1073741824)
            {
                return string.Format("{0}MB", fileLen/1048576);
            }
            return string.Format("{0}GB", fileLen / 1073741824);
        }



        #region EventHandler

        private void btnConnect_Click(object sender, EventArgs e)
        {
            Client.ConnectServer();
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            FrmSettings frmSettings = new FrmSettings();
            frmSettings.Show();
        }


        private void btnNewDownload_Click(object sender, EventArgs e)
        {
            FrmDownloadPrompt downloadPrompt = new FrmDownloadPrompt();
            downloadPrompt.Show();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string searchKey = this.tbSearchTxt.Text.Trim();
            Client.Search(searchKey);
        }


        #endregion

        #region Debug

        private void btnTest_Click(object sender, EventArgs e)
        {
            try
            {
                int b = 0;
                int a = 10/b;

            }
            catch(Exception ex)
            {
                CommonLogger.Logger.Error("Test Click()", ex);
            }
        }

        #endregion

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Client.Dispose();
        }


    }
}
